package com.zhe.zheblogmaster.handler.captcha;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.zhe.zheblogmaster.config.BlogConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 验证码处理器
 *
 * @author WHAOU
 * @date 2021/9/2
 * @email whaou@qq.com
 */
@Controller
public class CaptchaHandler {
    @Autowired
    private DefaultKaptcha captchaProducer;

    @GetMapping("/captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try (ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
             ServletOutputStream responseOutputStream = response.getOutputStream()) {
            // 生成验证码字符串
            String verifyCode = captchaProducer.createText();
            // 保存到session中
            request.getSession().setAttribute(BlogConstants.VERIFY_CODE, verifyCode);
            BufferedImage image = captchaProducer.createImage(verifyCode);
            ImageIO.write(image, "jpg", imgOutputStream);
            byte[] bytes = imgOutputStream.toByteArray();
            response.setHeader("Cache-Control", "no-store");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/jpeg");
            responseOutputStream.write(bytes);
            responseOutputStream.flush();
        } catch (IllegalArgumentException | IOException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
}
